import {
  getUserInfo,
  getRoutes,
  logout
} from '/service/service'
import {
  getRoleName
} from '/utils/rolesMap'
Page({
  data: {
    newFirstMenu: [],
    currentValidMenu: [{
      id: 'dispatch',
      title: '工单派遣',
      toPath: 'workOrderDispatch/workOrderDispatch',
      icon: 'dispatch.png',
      isEnable: true,
      bgColor: 'from-cyan-50-to-blue-50',
      iconColor: 'text-cyan-600',
      borderColor: '',
      shadowColor: 'shadow-cyan-100',
      isActive: false
    }, {
      id: 'approval',
      title: '工单审核',
      toPath: 'workOrderAudit/workOrderAudit',
      icon: 'approval.png',
      isEnable: true,
      bgColor: 'from-purple-50-to-pink-50',
      iconColor: 'text-purple-600',
      borderColor: '',
      shadowColor: 'shadow-purple-100',
      isActive: false
    }, {
      id: 'delay',
      title: '延期审核',
      toPath: 'delayReview/delayReview',
      icon: 'delay.png',
      isEnable: true,
      bgColor: 'from-amber-50-to-orange-50',
      iconColor: 'text-amber-600',
      borderColor: '',
      shadowColor: 'shadow-amber-100',
      isActive: false
    }, {
      id: 'inquiry',
      title: '工单查询',
      toPath: 'workOrderQuery/workOrderQuery',
      icon: 'inquiry.png',
      isEnable: true,
      bgColor: 'from-orange-50-to-red-50',
      iconColor: 'text-orange-600',
      borderColor: '',
      shadowColor: 'shadow-orange-100',
      isActive: false
    }, {
      id: 'process',
      title: '工单处理',
      toPath: 'workOrderProcessing/workOrderProcessing',
      icon: 'process.png',
      isEnable: true,
      bgColor: 'from-emerald-50-to-teal-50',
      iconColor: 'text-emerald-600',
      borderColor: '',
      shadowColor: 'shadow-emerald-100',
      isActive: false
    }, ],
    firstMenu: [{
        title: '工单管理',
        toPath: '',
        icon: '',
        haveChildrenMenu: [{
          title: '工单派遣',
          toPath: 'workOrderDispatch/workOrderDispatch',
          icon: '',
          isEnable: true
        }, {
          title: '工单审核',
          toPath: 'workOrderAudit/workOrderAudit',
          icon: '',
          isEnable: true
        }, {
          title: '延期审核',
          toPath: 'delayReview/delayReview',
          icon: '',
          isEnable: true
        }, {
          title: '工单查询',
          toPath: 'workOrderQuery/workOrderQuery',
          icon: '',
          isEnable: true
        }, {
          title: '工单处理',
          toPath: 'workOrderProcessing/workOrderProcessing',
          icon: '',
          isEnable: true
        }, ],
        isEnable: true
      },
      {
        title: '工作计划',
        toPath: '',
        icon: '',
        haveChildrenMenu: [{
          title: '全部工作',
          toPath: '',
          icon: '',
          isEnable: true
        }, ],
        isEnable: true
      },
      {
        title: '日常工作',
        toPath: '',
        icon: '',
        haveChildrenMenu: [{
            title: '例行工作列表',
            toPath: '',
            icon: '',
            isEnable: true
          },
          {
            title: '专项工作列表',
            toPath: '',
            icon: '',
            isEnable: true
          },
        ],
        isEnable: true
      },
      {
        title: '工作日报',
        toPath: 'workDailyReport/workDailyReport',
        icon: '',
        haveChildrenMenu: [],
        isEnable: true
      },
    ],
    mapInfo: {},
    address: '',
    refreshAddressLoading: false,
    refreshAddressId: null
  },
  onLoad() {
    this.getLocation()
    getUserInfo().then(res => {
      // console.log(res)
      const userLoginInfo = my.getStorageSync({
        key: 'user_login_info'
      }).data;
      if (userLoginInfo) {
        userLoginInfo.nickName = res.user.nickName
        userLoginInfo.role = res.roles[0]
      }
      my.setStorageSync({
        key: 'user_login_info',
        data: userLoginInfo
      })
    })
    getRoutes()
      .then(res => {
        // console.log('完整路由列表:', res);
        // 1. 找到“运维管理”路由（path: /IO）
        let ioRoute = null;
        if (res && res.length > 0) {
          // 遍历数组，找到path为/IO且非隐藏的路由
          for (let i = 0; i < res.length; i++) {
            const route = res[i];
            if (route.path === '/IO' && !route.hidden) {
              ioRoute = route;
              break;
            }
          }
        }

        if (!ioRoute) {
          console.log('未找到“运维管理”路由（path: /IO）');
          return [];
        }

        // 2. 找到“工单管理”路由（path: workOrder）
        let workOrderRoute = null;
        // 先判断ioRoute.children是否存在且为数组
        if (ioRoute.children && Array.isArray(ioRoute.children)) {
          for (let j = 0; j < ioRoute.children.length; j++) {
            const child = ioRoute.children[j];
            // 匹配path为workOrder，且name包含WorkOrder
            if (child.path === 'workOrder' && child.name && child.name.includes('WorkOrder')) {
              workOrderRoute = child;
              break;
            }
          }
        }

        if (!workOrderRoute || !workOrderRoute.children || !Array.isArray(workOrderRoute.children)) {
          console.log('未找到“工单管理”路由，或工单管理下无数据');
          return [];
        }

        // 3. 提取工单管理下的子数据
        const workOrderChildren = workOrderRoute.children;
        // console.log('运维管理-工单管理下的数据:', workOrderChildren);
        const titleArray = [];
        workOrderChildren.forEach(item => {
          if (item.meta && item.meta.title) {
            titleArray.push(item.meta.title);
          }
        });

        // console.log("提取的 title 数组：", titleArray);
        const {
          currentValidMenu
        } = this.data
        currentValidMenu.forEach(menuItem => {
          // 判断 menuItem.title 是否存在于 titleArray 中
          const isExist = titleArray.includes(menuItem.title);
          // 更新 isEnable
          menuItem.isEnable = isExist;
        });
        this.setData({
          currentValidMenu
        })
        this.filterEnableMenu()
      })
      .catch(err => {
        console.error('获取路由失败:', err);
      });
  },
  filterEnableMenu() {
    const {
      // firstMenu,
      currentValidMenu
    } = this.data;
    const filteredFirstMenu = currentValidMenu.filter(firstItem => {
      return firstItem.isEnable === true;
    }).map(firstItem => {
      const originalChildren = firstItem.haveChildrenMenu || [];
      const filteredChildren = originalChildren.filter(childItem => {
        return childItem.isEnable === true;
      });

      return {
        ...firstItem,
        haveChildrenMenu: filteredChildren
      };
    });

    this.setData({
      newFirstMenu: filteredFirstMenu
    });
  },
  toPath(e) {
    const {
      item
    } = e.currentTarget.dataset
    console.log(item)
    if (item.haveChildrenMenu.length > 0) {
      const menu = JSON.stringify(item.haveChildrenMenu)
      my.navigateTo({
        url: `../secondMenu/secondMenu?menu=${menu}`
      });
    } else {
      const path = item.toPath
      my.navigateTo({
        url: `../${path}`
      });
    }
  },
  handleLogout() {
    my.confirm({
      title: '退出登录',
      content: '确定要退出当前账号吗？',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      success: (res) => {
        if (res.confirm) {
          this.logoutConfirm()
        }
      }
    });
  },
  logoutConfirm() {
    logout().then(res => {
      console.log(res)
      if (res.code === 200) {
        // my.clearStorageSync();
        my.removeStorageSync({
          key: 'token'
        })
        my.reLaunch({
          url: '../index/index'
        });
      }
    })
  },
  getLocation() {
    if (this.data.refreshAddressLoading) return
    this.setData({
      refreshAddressLoading: true
    })
    const refreshAddressId = setTimeout(() => {
      dd.getLocation({
        targetAccuracy: '200',
        cacheTimeout: 20,
        coordinate: '1',
        useCache: true,
        withReGeocode: false,
        type: 1,
        success: (res) => {
          this.setData({
            mapInfo: res
          })
          const targetAddress = res.address.split('靠近')[1] || res.address;
          const cleanedAddress = targetAddress
            .replace(res.district, '')
            .replace(res.city, '')
            .replace(res.province, '')
            .trim();
          this.setData({
            address: cleanedAddress
          });
        },
        fail: () => {},
        complete: () => {
          this.setData({
            refreshAddressLoading: false,
            refreshAddressId: null
          })
        },
      });
    }, 500)
  },
  openMap() {
    const {
      latitude,
      longitude,
      address
    } = this.data.mapInfo
    if (latitude && longitude) {
      my.openLocation({
        longitude,
        latitude,
        title: address,
        address
      })
    } else {
      my.showToast({
        content: '点位信息不存在',
        type: 'fail'
      })
    }

  },
  copyData() {
    const copy = JSON.stringify(this.data.mapInfo)
    dd.setClipboard({
      text: copy,
    }).then(() => {
      dd.showToast({
        content: '地址信息已复制',
        type: 'success'
      })
    });
  }
});